<?php

	$url = $_GET["url"];
	$cachekey = $_GET["cachekey"];
	$output = $_GET["format"];

	// Caching using simple file swap cache. PHP4/PHP5
	// Caching code by Rasmus Lerdorf
	// February 1, 2006
	// Note: If you are using PHP 5.1 or newer, you can save
	// a system call by replacing time() with SERVER['REQUEST_TIME']

	// The ./ location puts the file in the root of your
	// web server,  usually
	define('CACHEDIR', './');

	$request =  $url;

	// If you make different types of requests, you'll want to implement
	// some sort of mapping from the request to unique filenames.
	$cache_filename = $cachekey;
	$cache_fullpath = CACHEDIR . $cache_filename;

	// Number of seconds until the cache gets stale
	$cache_timeout = 900;

	// Check the cache
	$response = request_cache($request, $cache_fullpath, $cache_timeout);

	if ($response === false) {
		die('Request failed');
	}

	echo $response;

	// This is the main caching routine. More robust error checking should
	// be implemented.
	function request_cache($url, $dest_file="", $timeout=900) {

		if(!file_exists($dest_file) || filemtime($dest_file) < (time()-$timeout)) {
			
			$ch = curl_init();	
			curl_setopt($ch, CURLOPT_URL, $url);	
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
			$data = curl_exec($ch);		
			curl_close($ch);
						
			if ($data === false) return false;
			
			$tmpf = tempnam('/tmp','YWS');
			$fp = fopen($tmpf,"w");
			fwrite($fp, $data);
			fclose($fp);
			rename($tmpf, $dest_file);
		
		} else {
			
			return file_get_contents($dest_file);
		
		}

		return($data);
	}

?>